package com.talos.ums.service.usertenant;

import com.talos.framework.common.pojo.PageResult;
import com.talos.framework.common.util.object.BeanUtils;
import com.talos.ums.controller.admin.usertenant.vo.UmsUserTenantPageReqVO;
import com.talos.ums.controller.admin.usertenant.vo.UmsUserTenantSaveReqVO;
import com.talos.ums.dal.dataobject.usertenant.UmsUserTenantDO;
import com.talos.ums.dal.mysql.usertenant.UmsUserTenantMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import static com.talos.framework.common.exception.enums.GlobalErrorCodeConstants.DATA_NOT_FOUND;
import static com.talos.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 用户租户表 Service 实现类
 *
 * @author ${table.author}
 */
@Service
@Validated
public class UmsUserTenantServiceImpl implements UmsUserTenantService {

    @Resource
    private UmsUserTenantMapper userTenantMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createUserTenant(UmsUserTenantSaveReqVO createReqVO) {
        // 插入
        UmsUserTenantDO userTenant = BeanUtils.toBean(createReqVO, UmsUserTenantDO.class);
        userTenantMapper.insert(userTenant);
        // 返回
        return userTenant.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUserTenant(UmsUserTenantSaveReqVO updateReqVO) {
        // 校验存在
        validateUserTenantExists(updateReqVO.getId());
        // 更新
        UmsUserTenantDO updateObj = BeanUtils.toBean(updateReqVO, UmsUserTenantDO.class);
        userTenantMapper.updateById(updateObj);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUserTenant(Long id) {
        // 校验存在
        validateUserTenantExists(id);
        // 删除
        userTenantMapper.deleteById(id);
    }

    private void validateUserTenantExists(Long id) {
        if (userTenantMapper.selectById(id) == null) {
            throw exception(DATA_NOT_FOUND);
        }
    }

    @Override
    public UmsUserTenantDO getUserTenant(Long id) {
        return userTenantMapper.selectById(id);
    }

    @Override
    public PageResult<UmsUserTenantDO> getUserTenantPage(UmsUserTenantPageReqVO pageReqVO) {
        return userTenantMapper.selectPage(pageReqVO);
    }

}
